var $productStatistics = $('#productStatistics');
var day = new Date().Format("yyyy.MM.dd") ;
var xData = [day]

$(function () {
    getBranchOfficeData()
    productStatisticsInit();
    chartInit('oderChart',[],[],[],[])
    $('#browsData input').on('click', function () {
        var dateType = $(this).val();
        if(dateType == 'day'){
            $('.statisticsName span').html('今天');
        }else if(dateType == 'thisWeek'){
            xData = getDateWeek();
            $('.statisticsName span').html('本周');
        }else if(dateType == 'thisMonth'){
            xData = createMonthDay();
            $('.statisticsName span').html('本月');
        }else if(dateType == 'topMonth'){
            xData = createMonthDay('-1');
            $('.statisticsName span').html('上月');
        }
        getOrderInfoList(dateType);
    })
    getOrderInfoList('day');
    getDateWeek();

    // 公司切换功能
    companiesList();
    $(document).on('click', function (e) {
        var target = $(e.target);
        if(!target.is('#companyList *')) {
            $('#companyList').collapse('hide');
        }
    });
    $(document).on('click', '#companyList a', function () {
        $('#companyList a').removeClass('active');
        $(this).addClass('active');
        $('#companyList').collapse('hide');
        $('#superCompanyName').html($(this).html() + '<i class="mdi mdi-chevron-down"></i>');

        var companyId = $(this).data('id');
        $('#companyId').val(companyId);

        // 顶部订单数据初始化
        getBranchOfficeData();
        // 订单统计
        getOrderInfoList($('#browsData input:checked').val());
        // 产品统计表
        productStatisticsInit();
    });

    $('.refresh-btn').on('click', function () {
        var $this = $(this);
        $this.prop('disabled', true);
        $this.find('i').addClass('mdi-spin');

        setTimeout(function () {
            $this.prop('disabled', false);
            $this.find('i').removeClass('mdi-spin');
        }, 300);
    });
})

//防止表头与表格不对齐
$(window).resize(function () {
    $productStatistics.bootstrapTable('resetView');
});


function getDateWeek(){
    var currentDate = new Date()
    var timesStamp = currentDate.getTime();
    var currenDay = currentDate.getDay();
    var dates = [];
    for (var i = 0; i < 7; i++) {
        dates.push(new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)).toLocaleDateString().replace(/\//g, '.'));
    }
    return dates
};

function createMonthDay(range) {
    let daysOfMonth = [];
    let fullYear = new Date().getFullYear();
    let month = new Date().getMonth() + 1 + Number(range || 0);
    let lastDayOfMonth = new Date(fullYear, month, 0).getDate();
    for (var i = 1; i <= lastDayOfMonth; i++) {
        daysOfMonth.push(fullYear + '.' + month + '.' + i);
    };
    // console.log(month + '月，有' + lastDayOfMonth + '天', daysOfMonth);
    return daysOfMonth;
}


function getBranchOfficeData(){
    $.ajax({
        url: '/order/financeIndexOrderInfo',
        type: 'POST',
        dataType:"json",
        contentType: "application/x-www-form-urlencoded",
        data:{
            companyId: $('#companyId').val()
        },
        // async:false,
        // processData: false,
        success:(function(data) {
            if(data.code == "000000") {
                $('#payBackToday').text(data.data.finishMoneyCount);
                $('#pendingPayment').text(data.data.waitCount);
                $('#refundToday').text(data.data.waitBackMoneyCount);
                if (isSuperCaiwu == '3') {
                    $('#superCompanyName').html(data.data.companyName + '<i class="mdi mdi-chevron-down"></i>');
                    $('#superCompanyName').prop('title', data.data.companyName);
                } else {
                    $('#companyName').html(data.data.companyName);
                }
            }
        }),
        error:(function() {

        })
    })
}

function getOrderInfoList(dateType) {
    let dom = document.getElementById('oderChart');
    let myChart = echarts.init(dom);
    myChart.showLoading();
    $('#rayBackNum, #refundNum, #performanceNum').text('...')

    $.ajax({
        url: '/order/financeIndexOrderInfoList',
        type: 'POST',
        dataType:"json",
        contentType: "application/x-www-form-urlencoded",
        data:{
            dateType: dateType,
            companyId: $('#companyId').val()
        },
        // async:false,
        // processData: false,
        success:(function(data) {
            if(data.code == "000000") {
                // console.log(data)
                $('#rayBackNum').text(data.data.returnMoneyCount)
                $('#refundNum').text(data.data.backMoneyCount);
                $('#performanceNum').text(data.data.gradeMoneyCount);
                chartInit('oderChart',xData,data.data.newVipCount,data.data.reNewCount,data.data.courseProductCount);
            }
        }),
        error:(function() {

        })
    })
}

//产品统计
function productStatisticsInit(){
    //先销毁表格
    $productStatistics.bootstrapTable('destroy');
    $productStatistics.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: ' /order/financeIndexOrderProductList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderId',
        idField: 'productOrderId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [5,10,15,20],//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'productOrderId', visible: false},
            {title: '产品名称',field: 'productName', align: 'left', valign: 'middle'},
            {title: '总计回款金额', field: 'returnMoney', align: 'left', valign: 'middle'},
            {title: '产品数量', field: 'productCount', align: 'left', valign: 'middle'},
            // {title: '退款状态', field: 'backStatus', align: 'right', valign: 'middle',formatter:function backStatusForm(value){
            //         if(value == 0){
            //             return '<span class=\'label label-info-light\'>审核中</span>'
            //         }else if(value == 1){
            //             return '<span class=\'label label-warning-light\'>未通过</span>'
            //         }else if(value == 2){
            //             return '<span class=\'label label-success-light\'>已通过</span>'
            //         }
            //     }},
            // {title: '操作', field: 'royaltyStatus', align: 'right', valign: 'middle',formatter: genderOpt },
        ],
        // data:[{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1},{orderNumber:1}],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.dateType = 'thisMonth';

    params.companyId = $('#companyId').val();
    return params;
}

function chartInit(id,xdata,newMember,membershipRenewal,course){
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        tooltip: {
            trigger: 'axis',
        },
        legend: {
            x:'right',
            padding:[17,30,0,0],
            data: ['会员新单', '会员续费', '课程产品']
        },
        color:['#856DFF','#456FFE','#20B784'],
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: xdata,
                axisLabel: {
                    textStyle: {
                        color: '#B4B4B4',//坐标值得具体的颜色
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: '#F2F2F2',
                    }
                },
            }
        ],
        yAxis: [
            {
                type: 'value',
                name:'(回款金额/万)',
                nameTextStyle:{
                    color:"#B4B4B4",
                    fontSize:14,
                },
                splitLine:{show: false},
                axisLabel: {
                    textStyle: {
                        color: '#B4B4B4',//坐标值得具体的颜色
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: '#F2F2F2',
                    }
                },
            }
        ],
        series: [
            {
                name: '会员新单',
                type: 'bar',
                barMaxWidth:'16',
                emphasis: {
                    focus: 'series'
                },
                itemStyle:{
                    normal:{
                        barBorderRadius:[4, 4, 0 , 0],
                    }
                },
                data: newMember
            },
            {
                name: '会员续费',
                type: 'bar',
                barMaxWidth:'16',
                emphasis: {
                    focus: 'series'
                },
                itemStyle:{
                    normal:{
                        barBorderRadius:[4, 4, 0 , 0],
                    }
                },
                data: membershipRenewal
            },
            {
                name: '课程产品',
                type: 'bar',
                barMaxWidth:'16',
                data: course,
                emphasis: {
                    focus: 'series'
                },
                itemStyle:{
                    normal:{
                        barBorderRadius:[4, 4, 0 , 0],
                    }
                },
            },

        ]
    };
    myChart.setOption(option);
    myChart.hideLoading();  // 获取数据后关闭加载动画
    window.addEventListener("resize",function(){
        myChart.resize();
    });
}

/**
 * 功能：获取分公司列表
 * 接口：罗杰
 * */
function companiesList() {
    $.ajax({
        url: '/sysCompany/selectCompanies',
        type: 'GET',
        dataType: "json",
        success:(function(data) {
            if(data.code == "000000") {
                var companyData = data.data;
                var listDom = '<li><a href="#!" data-id="" class="active">总部财务部</a></li>';
                for (let i = 0; i < companyData.length; i++) {
                    listDom += '<li><a href="#!" data-id="' + companyData[i].companyId + '">' + companyData[i].companyName + '</a></li>';
                }
                $('#companyList ul').html(listDom);
            } else {
                $.alert({
                    title: '错误提醒',
                    content: '分公司列表数据请求出错，错误代码：' + data.code
                });
            }
        }),
        error:(function(err) {
            $.alert({
                title: '失败提醒',
                content: '分公司列表数据请求失败'
            });
            console.log(err);
        })
    });
}